import React, { useState, useEffect } from 'react'
import { Table, Button, Input, Modal, Form, message, Select, Space, Popconfirm, InputNumber, Dropdown, Tag } from 'antd';
import axios from 'axios';
import { DatasetComponent } from 'echarts/components';
export default function Logisticsmanage() {
  const [dataSource, setDataSource] = useState([])
  const [messageApi, contextHolder] = message.useMessage();
  const [open, setOpen] = useState(false);
  const [nowItem, setNowItem] = useState("");
  const [goodsList, setGoodsList] = useState([])
  const [saleList, setSaleList] = useState([])
  const [selectQue, setSelectQue] = useState([])
  const [selectionType, setSelectionType] = useState('checkbox');
  useEffect(() => {
    getData()
    axios.get("/goods/selectall").then(res => {
      setGoodsList(res.data)
    })

  }, [])
  const getData = () => {
    axios.get("/logistics/selectall").then(res => {
      setDataSource(res.data)
    })
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: "center",
      width: "10%",
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{index + 1}</span>
      }
    },
    {
      title: '订单名称',
      dataIndex: 'ordername',
      key: 'ordername',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '销售订单名称',
      dataIndex: 'saleordername',
      key: 'saleordername',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '物流状态',
      dataIndex: 'logisticstate',
      key: 'logisticstate',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text === 0 ? "未发货" : "已发货"}</span>
      }
    },
    {
      title: '下单时间',
      dataIndex: 'ordertime',
      key: 'ordertime',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '发货时间',
      dataIndex: 'deliverytime',
      key: 'deliverytime',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text === null ? "无" : text}</span>
      }
    },

    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      fixed: 'right',
      align: "center",
      render: (text, item) => {
        return <Space>
          <a style={{ fontSize: "12px", color: item.logisticstate === 1 ? "gray" : "#4e9dfd" }} disabled={item.logisticstate === 1} onClick={() => { if (item.deliverytime === null) { updateOrder(item); setOpen(true); setNowItem(item); } }}>修改</a>
          <Popconfirm
            title={"删除"}
            description={"确定删除该订单?"}
            okText="确定"
            cancelText="取消"
            onConfirm={() => { deleteGoods(item) }}
            disabled={item.logisticstate === 1}
          >
            <a style={{ fontSize: "12px", color: item.logisticstate === 1 ? "gray" : "red" }} disabled={item.logisticstate === 1}>{"删除"}</a>
          </Popconfirm>
          <Popconfirm
            title={"发货"}
            description={"确定发货吗?"}
            okText="确定"
            cancelText="取消"
            onConfirm={() => { delivery(item) }}
            disabled={item.logisticstate === 1}
          >
            <a style={{ fontSize: "12px", color: item.logisticstate === 1 ? "gray" : "red" }} disabled={item.logisticstate === 1}>{"发货"}</a>
          </Popconfirm>
        </Space >
      }
    }
  ];
  const delivery = (item) => {
    axios.get("/logistics/dodelivery?id=" + item.id + "&&saleId=" + item.saleid).then(res => {
      if (res.data) {
        messageApi.open({
          type: 'success',
          content: '发货成功',
        });
        var nowdata = [...dataSource]
        let targetObject = nowdata.find(obj => obj.id === res.data.id);
        if (targetObject) {
          targetObject.deliverytime = res.data.deliverytime;
          targetObject.logisticstate = res.data.logisticstate;
        }
        setDataSource(nowdata)
      }
    })
  }
  const updateOrder = (item) => {
    setOpen(true);
    setNowItem(item);
    setSelectQue([item.saleid])
    axios.get("/sale/selectproduced").then(res => {
      setSaleList(res.data)
    })
    form.setFieldsValue({
      ordername: item.ordername,
    })
  }
  const columns1 = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: "center",
      width: "10%",
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{index + 1}</span>
      }
    },
    {
      title: '订单名称',
      dataIndex: 'ordername',
      key: 'ordername',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '销售商品',
      dataIndex: 'goodsid',
      key: 'goodsid',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{goodsList.filter(res => { return res.id === text })[0]?.goodsname}</span>
      }
    },
    {
      title: '商品数量',
      dataIndex: 'goodsnum',
      key: 'goodsnum',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '下单时间',
      dataIndex: 'ordertime',
      key: 'ordertime',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '生产开始时间',
      dataIndex: 'prostartime',
      key: 'prostartime',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text === null ? "无" : text}</span>
      }
    },
    {
      title: '生产完成时间',
      dataIndex: 'proendtime',
      key: 'proendtime',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text === null ? "无" : text}</span>
      }
    },
  ];
  const deleteGoods = (item) => {
    if (item.deliverytime === null) {
      axios.get("/logistics/delete?id=" + item.id).then(res => {
        if (res.data > 0) {
          messageApi.open({
            type: 'success',
            content: '删除成功',
          });
          setDataSource(dataSource.filter(res => { return res.id !== item.id }))
        }
      })
    } else {
      messageApi.open({
        type: 'warning',
        content: '不可删除！',
      });
    }

  }
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectQue(selectedRowKeys)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
    selectedRowKeys: selectQue
  };
  const [form] = Form.useForm();
  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    return (
      <Form
        form={form}
        layout="vertical"
        name="form_in_modal"
      >
        <Form.Item
          name="ordername"
          label="订单名称"
          rules={[
            {
              required: true,
              message: '未输入订单名称！',
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Table
          rowSelection={{
            type: selectionType,
            ...rowSelection,
          }}
          columns={columns1} dataSource={saleList} style={{ margin: "5px 0 0 0" }}
          rowKey={(item) => item.id}
          pagination={{}}
          size='small'
        >
        </Table>
      </Form>
    );
  };
  const onCreate = (values) => {
    if (selectQue.length === 1) {
      if (nowItem !== "") {
        axios.post("/logistics/update", {
          id: nowItem.id,
          ...values,
          saleid: selectQue[0]
        }).then(res => {
          if (res.data) {
            messageApi.open({
              type: 'success',
              content: '修改成功',
            });
            var nowdata = [...dataSource]
            let targetObject = nowdata.find(obj => obj.id === nowItem.id);
            if (targetObject) {
              targetObject.ordername = values.ordername;
              targetObject.saleid = res.data.saleid;
              targetObject.saleordername = saleList.filter(obj => { return obj.id === res.data.saleid })[0].ordername
            }
            setDataSource(nowdata)
            setNowItem("")
          }
        })
      } else {
        axios.post("/logistics/insert", {
          ...values,
          saleid: selectQue[0]
        }).then(res => {
          if (res.data) {
            messageApi.open({
              type: 'success',
              content: '添加成功',
            });
            var data = res.data
            for (var i = 0; i < saleList.length; i++) {
              if (saleList[i].id === data.saleid) {
                data.saleordername = saleList[i].ordername
              }
            }
            setDataSource([...dataSource, data])

          }
        })
      }
      setOpen(false);
      form.resetFields();
      setSelectQue([])
    } else {
      messageApi.open({
        type: 'warning',
        content: '请选择一个订单',
      });
    }
  };
  const opGoods = () => {
    setOpen(true)
    form.setFieldsValue({
      ordername: "",
    })
    axios.get("/sale/selectproduced").then(res => {
      var data = []
      var idlist = []
      dataSource.forEach(element => {
        idlist.push(element.saleid)
      });
      for (var i = 0; i < res.data.length; i++) {
        if (!idlist.includes(res.data[i].id)) {
          data.push(res.data[i])
        }
      }
      setSaleList(data)
    })
  }
  return (
    <div>
      <div >
        {contextHolder}
        <div style={{ display: 'flex' }}>
          <div style={{ flex: "1 1 100px" }}>
            <div><Button type="primary" onClick={() => { opGoods() }}>新增物流</Button></div>
          </div>
          <div style={{ flex: "1 1 100px", textAlign: "right" }}>
            <Button onClick={() => { getData() }}>刷新</Button>
          </div>
        </div>

        <Table
          columns={columns} dataSource={dataSource} style={{ margin: "5px 0 0 0" }}
          rowKey={(item) => item.id}
          pagination={{ pageSize: 10 }}
          size='small'
        >
        </Table>
      </div>
      <Modal
        open={open}
        title={nowItem !== "" ? "修改订单" : "新增订单"}
        okText="确定"
        cancelText="取消"
        onCancel={() => { setOpen(false); setNowItem(""); setSaleList([]); setSelectQue([]) }}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {

              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
        width={"1000px"}
      >
        <CollectionCreateForm
        />
      </Modal>

    </div>
  )
}
